//
//  SettingsLoadingVC.m
//  JingRong_Safe_IDLFaceSDKDemoOC
//
//  Created by 万事如意 on 2025/9/1.
//  Copyright © 2025 Baidu. All rights reserved.
//

#import "SettingsLoadingVC.h"
#import "NSString+Tool.h"
#import "BDFaceAgreementViewController.h"
#import "JTStartViewController.h"




@interface SettingsLoadingVC ()

@property (nonatomic, strong) UIImageView *launchImgView;

@property (nonatomic, strong) UIButton *reRequestInfo;

@property (nonatomic, strong) UIActivityIndicatorView *activityView;


@end

@implementation SettingsLoadingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.launchImgView = [[UIImageView alloc] initWithFrame:APPWINDOW.bounds];
    self.launchImgView.image = [UIImage imageNamed:@"launchImage"];
    self.launchImgView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:self.launchImgView];
    
    self.reRequestInfo = [[UIButton alloc]  initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    [self.reRequestInfo setTitle:@"初始化网络连接失败,\n轻点重新尝试" forState:UIControlStateNormal];
    self.reRequestInfo.titleLabel.numberOfLines = 2;
    self.reRequestInfo.hidden = YES;
    self.reRequestInfo.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.reRequestInfo.center = CGPointMake(self.view.center.x, kScreenHeight*2/3+50);
    [self.reRequestInfo addTarget:self action:@selector(verifyPlacePad) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.reRequestInfo];
    
    self.activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleMedium];
    self.activityView.frame = CGRectMake(0, 0, 100, 100);
    self.activityView.center = APPWINDOW.center;
    self.activityView.backgroundColor = [UIColor colorWithRed:217/255.0 green:223/255.0 blue:230/255.0 alpha:1];
    self.activityView.layer.cornerRadius = 8;
    [self.activityView startAnimating];
    [APPWINDOW addSubview:self.activityView];
}

- (void)verifyPlacePad {
    [self.activityView startAnimating];
    //设备ID
    NSString *udid =[UUIDManager getUUID];
    //日期处理
    NSDate *date = [NSDate date];
    NSTimeInterval interval = [date timeIntervalSince1970];
    NSString *intervalStr = [NSString stringWithFormat:@"%.0f",interval*10000];
    //32位随机数
    NSString *nonceStr = [NSString stringWithFormat:@"%ld",(long)(arc4random()*pow(10, 31))];
    NSString *placeKey = @"";
    //sign 签名
    NSString *secretKey = @"7dkc86acd1438f1";
    NSString *paramStr = [NSString stringWithFormat:@"%@%@%@",udid, intervalStr,nonceStr];
    NSString *signStr = [paramStr HmacSHA256WithSecretKey:secretKey];
    NSString *version = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //参数处理+
    NSDictionary *dict = @{@"deviceId":udid,@"timestamp":intervalStr,@"nonceStr":nonceStr,@"placeKey":placeKey,@"sign":signStr,@"attendanceVersion":version};
    NSMutableArray *marr = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    NSString *bodyStr = [marr componentsJoinedByString:@"&"];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",Base_Url,POST_GETPLACEINFO]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = 30;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                DLog(@"%@",responseDic);
                self.reRequestInfo.hidden = YES;
                NSDictionary *dict = (NSDictionary *)responseDic;
                NSNumber *code = (NSNumber *)[dict objectForKey:@"code"];
                NSString *msg = (NSString *)[dict objectForKey:@"msg"];
                NSDictionary *dataDict = (NSDictionary *)[dict objectForKey:@"data"];
                [self.activityView stopAnimating];
                if (![code isEqualToNumber:@(0)]) {
                    
                    [AdminInfo shareInfo].placeKey = @"";
                    [AdminInfo shareInfo].placeName = @"";
                    [AdminInfo shareInfo].placeId = @"";
                    [AdminInfo shareInfo].adapterAppID = @"";
                    [AdminInfo shareInfo].enableLiveness = @"1";
                } else {
                    [AdminInfo shareInfo].placeKey = [dataDict objectForKey:@"appKey"];
                    [AdminInfo shareInfo].placeId = [dataDict objectForKey:@"iD"];
                    [AdminInfo shareInfo].placeName = [dataDict objectForKey:@"placeName"];
                    [AdminInfo shareInfo].adapterAppID = [dataDict objectForKey:@"adapterAppID"];
                    [AdminInfo shareInfo].enableLiveness = NSStringFormate(@"%@",[dataDict objectForKey:@"livingBody"]);
                }
                if ([AdminInfo shareInfo].hasAgree) {
                    [self enterHome];
                } else {
                    [self agreenmentAlert];
                }
            });
        } else {
            [self.activityView stopAnimating];
            if (error.code == -1009) {
                self.reRequestInfo.hidden = NO;
            } else {
                [AdminInfo shareInfo].placeKey = @"";
                [AdminInfo shareInfo].placeName = @"";
                [AdminInfo shareInfo].adapterAppID = @"";
                [AdminInfo shareInfo].enableLiveness = @"1";
                NSLog(@"%@",error.localizedDescription);
            }
        }
    }];
    [task resume];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self verifyPlacePad];
}

- (void)agreenmentAlert {
    BDFaceAgreementViewController *vc = [[BDFaceAgreementViewController alloc] init];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void)enterHome {
    APPWINDOW.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[JTStartViewController alloc] init]];
    
}

@end
